package org.yu.api.register.data;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DataProvider;
import net.minecraft.data.HashCache;
import net.minecraftforge.common.data.ExistingFileHelper;
import org.yu.api.register.LazyRegistry;

import java.io.File;
import java.io.IOException;

public abstract class LazyGeneratorBase implements DataProvider {
    protected final Gson gson;
    protected final LazyRegistry lazyRegistry;
    protected final DataGenerator generator;
    protected final ExistingFileHelper fileHelper;

    public LazyGeneratorBase(LazyRegistry lazyRegistry, DataGenerator generator, ExistingFileHelper fileHelper) {
        this.lazyRegistry = lazyRegistry;
        this.generator = generator;
        this.fileHelper = fileHelper;
        this.gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
    }



    protected void saveData(JsonElement jsonElement, String dir, String name, HashCache hashCache) {
        File dirPath = new File(getDataDirection(), dir);
        dirPath.mkdirs();
        try {
            DataProvider.save(gson, hashCache, jsonElement, new File(dirPath, name + ".json").toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    protected void saveAssets(JsonElement jsonElement, String dir, String name, HashCache hashCache) {
        File dirPath = new File(getAssetsDirection(), dir);
        dirPath.mkdirs();
        try {
            DataProvider.save(gson, hashCache, jsonElement, new File(dirPath, name + ".json").toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    protected void saveAssets(String modid,JsonElement jsonElement, String dir, String name, HashCache hashCache) {
        File dirPath = new File(getAssetsDirection(modid), dir);
        dirPath.mkdirs();
        try {
            DataProvider.save(gson, hashCache, jsonElement, new File(dirPath, name + ".json").toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    protected File getDataDirection() {
        return getDataDirection(lazyRegistry.getModID());
    }
    protected File getDataDirection(String modid) {
        return getDirection("data",modid);
    }
    protected File getDirection(String pkgType,String modid) {
        File dataFile = new File(generator.getOutputFolder().toFile(), pkgType+'/' + modid);
        dataFile.mkdirs();
        return dataFile;
    }
    protected File getAssetsDirection(String modid) {
        return getDirection("assets",modid);
    }
    protected File getAssetsDirection() {
        return getAssetsDirection( lazyRegistry.getModID());
    }

    @Override
    public String getName() {
        return getClass().getSimpleName()+" For "+lazyRegistry.getModID();
    }
}
